package com.rjgc.emallsimulation.controller;

import com.rjgc.emallsimulation.entity.User;
import com.rjgc.emallsimulation.service.UserService;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.awt.*;
import java.time.LocalDate;
import java.util.HashMap;
import java.util.Map;

@RestController
public class LoginController {

    @Resource
    UserService userService;

    @PostMapping("/login")
    public Map<String,Object> login(
            @RequestParam("phone") String phone,
            @RequestParam("password") String password,
            HttpServletRequest request
    ){
        Map<String,Object> result=new HashMap<>();
        User user=userService.query()
                .eq("phone",phone)
                .eq("password",password).one();
        if(user!=null){
            request.getSession().setAttribute("userinfo",phone);
            result.put("LoginSuccess",true);
            result.put("identify",user.getIdentity());
            return result;
        }else {
            result.put("LoginSuccess",false);
            result.put("identify",null);
            return result;
        }
    }

    @PostMapping("/logout")
    public Map<String,Boolean> login(HttpServletRequest request){
        Map<String,Boolean> result=new HashMap<>();
        HttpSession session = request.getSession();
        session.removeAttribute("userinfo");
        Object user = session.getAttribute("userInfo");
        if(user==null){
            result.put("LogoutSuccess",true);
        }else {
            result.put("LogoutSuccess",false);
        }
        return result;
    }

    @PostMapping("/register")
    public Map<String,Boolean> register(@RequestParam("name") String name,
                                        @RequestParam("password") String password,
                                        @RequestParam("phone") String phone,
                                        @RequestParam("identity") String identity
    ){
        Map<String,Boolean> result=new HashMap<>();
        User user=new User();
        String accountStr=String.valueOf(System.currentTimeMillis());
        user.setAccount(accountStr.substring(accountStr.length()-6));
        user.setName(name);
        user.setPhone(phone);
        user.setPassword(password);
        user.setIdentity(identity);
        boolean flag=userService.save(user);
        if(flag){
            result.put("RegisterSuccess",true);
        }else {
            result.put("RegisterSuccess",false);
        }
        return result;

    }
}
